//
//  DateUtils.swift
//  cad
//
//  Created by 灵工邦 on 2024/6/12.
//

import Foundation

class DateUtils {
    
    static func daysBetweenDates(startDate: String, endDate: String) -> Int {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"
        
        guard let date1 = dateFormatter.date(from: startDate),
              let date2 = dateFormatter.date(from: endDate) else {
            return 0
        }
        
        let calendar = Calendar.current
        let dateComponents: Set<Calendar.Component> = [.year, .month, .day]
        
        let components1 = calendar.dateComponents(dateComponents, from: date1)
        let components2 = calendar.dateComponents(dateComponents, from: date2)
        
        guard let adjustedDate1 = calendar.date(from: components1),
              let adjustedDate2 = calendar.date(from: components2) else {
            return 0
        }
        
        if calendar.compare(adjustedDate1, to: adjustedDate2, toGranularity: .day) == .orderedSame {
            return 1
        }
        
        let components = calendar.dateComponents([.day], from: adjustedDate1, to: adjustedDate2)
        return (components.day ?? 0) + 1
    }
    
    static func isEarlierThan(startTimeString: String, endTimeString: String) -> Bool {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "HH:mm"
        
        guard let date1 = dateFormatter.date(from: startTimeString),
              let date2 = dateFormatter.date(from: endTimeString) else {
            return false
        }
        
        let calendar = Calendar.current
        let unit: Set<Calendar.Component> = [.hour, .minute]
        
        let components1 = calendar.dateComponents(unit, from: date1)
        let components2 = calendar.dateComponents(unit, from: date2)
        
        guard let time1 = calendar.date(from: components1),
              let time2 = calendar.date(from: components2) else {
            return false
        }
        
        let result = calendar.compare(time1, to: time2, toGranularity: .minute)
        
        return result == .orderedDescending || result == .orderedSame
    }
    
    static func isDateWithinThreeDaysBeforeToday(_ date: Date) -> Bool {
        let calendar = Calendar.current
        // 获取今天的起始时间
        let today = calendar.startOfDay(for: Date())
        // 计算三天前的日期
        if let threeDaysAgo = calendar.date(byAdding: .day, value: -3, to: today) {
            // 获取目标日期的起始时间
            let targetDate = calendar.startOfDay(for: date)
            // 判断目标日期是否在三天前到今天的范围内
            return targetDate >= threeDaysAgo && targetDate <= today
        }
        return false
    }
}
